package com.feib.soeasy.action;

import java.io.StringReader;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.feib.soeasy.model.UserActionLog;

import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.validation.ValidationError;
import net.sourceforge.stripes.validation.ValidationErrors;

/**
 * @title (#)BaseActionBean.java<br>
 * @description 基礎類別<br>
 * @author Jimmy Liu<br>
 * @version 1.0.0 2010/11/25
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @20101025 create by Jimmy Liu<br>
 */
public class BaseActionBean implements ActionBean {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    private BaseActionBeanContext ctx;

    @Override
    public ActionBeanContext getContext() {
        return ctx;
    }

    @Override
    public void setContext(ActionBeanContext context) {
        this.ctx = (BaseActionBeanContext) context;
        preBind();
    }

    /**
     * 
     */
    protected void preBind() {
        
    }

    /**
     * data binding 錯誤處理<br>
     * Allows the ActionBean to influence what happens when validation errors occur during
     * validation and binding.
     * 
     * @param errors the set of validation errors generated during validation and binding
     * @retur nnull, or a Resolution specifying what should happen next if non-standard
     *        behaviour is desired
     * @throws Exception may throw any exception, but this will generally result in a
     *         ServletException being thrown on up the stack
     */
    public Resolution handleValidationErrors(ValidationErrors errors) throws Exception 
    {
        String event = this.getContext().getEventName();
        if (null != event)
        {
            event = event.toLowerCase();

            // 如果是 ajax 的呼叫，則回傳  html fragments
            if ( -1  != event.indexOf("ajax"))
            {
                return errorsToHtmlStreams(errors);
            }
        }

        // 其他錯誤，由原本頁面處理或客制畫面處理
        return handleValidationErrorsForward();
    }

    /**
     * 導致錯誤處理頁面
     * @return 錯誤頁面 Resolution
     */
    protected Resolution handleValidationErrorsForward()
    {
        return this.getContext().getSourcePageResolution();
    }

    /**
     * Converts errors to HTML and streams them back to the browser
     * @param errors
     * @return
     */
    protected Resolution errorsToHtmlStreams(ValidationErrors errors)
    {
        StringBuilder message = new StringBuilder();
        message.append("<div id=\"validationErrorDiv\">");
        for (List<ValidationError> fieldErrors : errors.values()) {
            for (ValidationError error : fieldErrors) {
                message.append("<div class=\"error\">");
                message.append(error.getMessage(getContext().getLocale()));
                message.append("</div>");
            }
        }
        message.append("</div>");
        
        message.append("<script type=\"text/javascript\">");
        message.append("$(document).ready(function() {");
        message.append("$( \"#validationErrorDiv\" ).dialog( \"destroy\" );");
        message.append("$( \"#validationErrorDiv\" ).dialog({  title:'請修正下列錯誤' ,width: 300, resizable: false, modal: true  });");
        message.append("});");
        
        StreamingResolution resolution = new StreamingResolution("text/html", new StringReader(message.toString()));
        resolution.setCharacterEncoding("UTF-8");
        return resolution;
    }
    
    protected void addAccessLog(String note)
    {
        addAccessLog(note, true);
    }
    
    protected void addAccessLog(String note, boolean append)
    {
        try {
            HttpServletRequest request = this.getContext().getRequest();
            UserActionLog actionLog = (UserActionLog) request.getAttribute(UserActionLogInterceptor.ACCESS_LOG_KEY);
            if (null == actionLog)
                return;
            
            StringBuffer logNote = new StringBuffer();
            if (append)
                logNote.append(null == actionLog.getLogNote() ? "" : actionLog.getLogNote()+"; ");
            
            logNote.append(note);
            
            actionLog.setLogNote(logNote.toString());
            
            logNote = null;
            
        }
        catch (Exception e) {
            logger.error("加入操作LOG說明錯誤：", e);
        }
    }
}
